package com.sunjs.pay.service.impl;

import java.sql.Timestamp;
import java.util.Date;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.sunjs.common.kit.HttpClientUtil;
import com.sunjs.model.Payment;
import com.sunjs.pay.config.PayConfig;
import com.sunjs.pay.dao.PaymentMapper;
import com.sunjs.pay.properties.Properties;
import com.sunjs.pay.service.PaymentService;
import com.sunjs.pay.util.PayUtil;

@Service
public class PaymentServiceImpl implements PaymentService {
	private static Logger LOGGER = LoggerFactory.getLogger(PaymentServiceImpl.class);
	@Autowired
	private Properties properties;
	
	@Autowired
	private PaymentMapper paymentMapper;
	

	@Override
	public Map<String, Object> xcxPayment(String body, String orderNum, double money, String openId) throws Exception {
		LOGGER.info("【小程序支付】 统一下单开始, 订单编号=" + orderNum);
		SortedMap<String, Object> resultMap = new TreeMap<String, Object>();
		Map<String, String> resMap = this.xcxUnifieldOrder(body, orderNum, PayConfig.TRADE_TYPE_JSAPI, money,
				openId);
		if ("SUCCESS".equals(resMap.get("return_code")) && "SUCCESS".equals(resMap.get("result_code"))) {
			resultMap.put("appId", properties.getAppid());
			resultMap.put("timeStamp", PayUtil.getCurrentTimeStamp());
			resultMap.put("nonceStr", PayUtil.makeUUID(32));
			resultMap.put("package", "prepay_id=" + resMap.get("prepay_id"));
			resultMap.put("signType", "MD5");
			resultMap.put("paySign", PayUtil.createSign(resultMap, properties.getKey()));
			resultMap.put("returnCode", "SUCCESS");
			resultMap.put("returnMsg", "OK");
			LOGGER.info("【小程序支付】统一下单成功，返回参数:" + resultMap);
		} else {
			resultMap.put("returnCode", resMap.get("return_code"));
			resultMap.put("returnMsg", resMap.get("return_msg"));
			LOGGER.info("【小程序支付】统一下单失败，失败原因:" + resMap.get("return_msg"));
		}
		return resultMap;
	}

	/**
	 * 小程序支付统一下单
	 */
	private Map<String, String> xcxUnifieldOrder(String body, String orderNum, String tradeType, double payAmount,
			String openid) throws Exception {
		// 封装参数
		SortedMap<String, Object> paramMap = new TreeMap<String, Object>();
		paramMap.put("appid", properties.getAppid());
		paramMap.put("mch_id", properties.getMchId());
		paramMap.put("nonce_str", PayUtil.makeUUID(32));
		paramMap.put("body", body);
		paramMap.put("out_trade_no", orderNum);
		paramMap.put("total_fee", PayUtil.moneyToIntegerStr(payAmount));
		paramMap.put("spbill_create_ip", PayUtil.getLocalIp());
		paramMap.put("notify_url", properties.getNotifyUrl() + "/payment/xcxNotify");
		paramMap.put("trade_type", tradeType);
		paramMap.put("openid", openid);
		paramMap.put("sign", PayUtil.createSign(paramMap, properties.getKey()));
		// 转换为xml
		String xmlData = PayUtil.mapToXml(paramMap);
		// 请求微信后台，获取预支付ID
		String resXml = HttpClientUtil.httpRequest(PayConfig.WX_PAY_UNIFIED_ORDER, "POST", xmlData);
		LOGGER.info("【小程序支付】 统一下单响应：\n" + resXml);
		LOGGER.info("【小程序支付】 小程序支付统一下单参数：\n" + paramMap);
		return PayUtil.xmlStrToMap(resXml);
	}

	/**
	 * 支付回调方法
	 */
	@Override
	@Transactional(readOnly = false, rollbackFor = { Exception.class })
	public int xcxNotify(Map<String, Object> map) throws Exception {
	    LOGGER.info("【小程序支付】回调开始=============="+map);
	    Date date = new Date();       
		Timestamp newDate = new Timestamp(date.getTime());
		Payment payment = new Payment();
	    
		payment.setPayTime(newDate);
		payment.setStatus(0); // 0，已支付
	    // 修改支付表状态
	    paymentMapper.updatePaymentStatus(payment);
		
		return 0;
	}

	/**
	 * 获取订单
	 */
	@Override
	public Payment getPayment(Payment payment) throws Exception {
		return paymentMapper.getPayment(payment);
	}
}
